package com.hbnu.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author kittychen
 * @since 2025-10-28 19:37
 */
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器已启动，等待连接....");

            Socket socket = serverSocket.accept();  // 等待客户端连接,accept()是一个阻塞方法，如果没有客户端连接，会一直等待

            InputStream inputStream = socket.getInputStream();

            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            System.out.println("客户端发送的数据是：" + new String(buffer, 0, len));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
